package com.kehongborui.spring.interceptor;

import com.kehongborui.spring.controller.LoginController;
import com.kehongborui.spring.model.UserModel;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief 用户登录拦截（判断用户是否登录）
 * @email 122162005@qq.com
 * @date 2018-08-02
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 获取登录用户
        UserModel user = (UserModel) httpServletRequest.getSession().getAttribute(LoginController.LOGIN_USER);
        // 如果用户在访问资源时没有登录，就重定向到错误页面
        if (user == null) {
            httpServletResponse.sendRedirect("/error.do");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
